package com.waitingsnow.modules.shell.view.baseView
{
import assets.shellView.TipAsset;
import assets.shellView.VideoSetAsset;

import com.waitingsnow.core.debug.Logger;
import com.waitingsnow.core.model.config.AppConfig;
import com.waitingsnow.modules.shell.model.vo.RubyServerVO;
import com.waitingsnow.modules.shell.model.vo.VideoSetVO;
import com.waitingsnow.modules.shell.view.controls.Alert;
import com.waitingsnow.modules.shell.view.video.PlayVideoContainer;
import com.waitingsnow.modules.shell.view.video.PublishVideo;
import com.waitingsnow.modules.shell.view.video.events.PlayVideoEvent;
import com.waitingsnow.modules.shell.view.video.events.PublishVideoEvent;

import fl.controls.Button;
import fl.controls.ComboBox;
import fl.controls.Slider;
import fl.data.DataProvider;
import fl.events.SliderEvent;

import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.media.Camera;
import flash.media.Microphone;
import flash.system.Security;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;

/**
 * 
 * @author waitingsnow
 * $Id: VideoSetView.as 2 2012-05-17 10:10:03Z cgslendy@gmail.com $
 */
public class VideoSetView extends Sprite
{
	//==========================================================================
	//  Constructor
	//==========================================================================
	/**
	 * Constructs a new <code>VideoSetView</code> instance.
	 * 
	 */
	public function VideoSetView()
	{
		initDisplay();
	}
	
	//==========================================================================
	//  Variables
	//==========================================================================
	private var videoSetAsset:VideoSetAsset;
	private var video_cb:ComboBox;
	private var audio_cb:ComboBox;
	private var videoRadio_cb:ComboBox;
	private var videoFrame_sl:Slider;
	private var inputAudio_sl:Slider;
	private var ok_btn:Button;
	private var cancel_btn:Button;
	
	private var videoSetVO:VideoSetVO;
	private var publishVideo:PublishVideo;
	private var playVideoContainer:PlayVideoContainer;
	private var tipAsset:TipAsset;
	
	//==========================================================================
	//  Properties
	//==========================================================================
	private var _rubyServerVO:RubyServerVO;
	public function set rubyServerVO(value:RubyServerVO):void
	{
		_rubyServerVO = value;
	}
	
	//==========================================================================
	//  Methods
	//==========================================================================
	private function initDisplay():void
	{
		videoSetVO = new VideoSetVO();
	}
	
	private function initVideoSet():void
	{
		videoSetAsset = new VideoSetAsset();
		video_cb = new ComboBox();
		video_cb.x = 20;
		video_cb.y = 65;
		video_cb.setSize(144, 22);
		videoSetAsset.addChild(video_cb);
		audio_cb = new ComboBox();
		audio_cb.x = 20;
		audio_cb.y = 175;
		audio_cb.setSize(144, 22);
		videoSetAsset.addChild(audio_cb);
		videoRadio_cb = new ComboBox();
		videoRadio_cb.x = 245;
		videoRadio_cb.y = 65;
		videoRadio_cb.setSize(90, 22);
		videoSetAsset.addChild(videoRadio_cb);
		videoFrame_sl = new Slider();
		videoFrame_sl.x = 250;
		videoFrame_sl.y = 100;
		videoFrame_sl.width = 65;
		videoFrame_sl.minimum = 1;
		videoFrame_sl.maximum = 25;
		videoFrame_sl.addEventListener(SliderEvent.CHANGE, videoFrameChangeHandler);
		videoSetAsset.addChild(videoFrame_sl);
		inputAudio_sl = new Slider();
		inputAudio_sl.x = 250;
		inputAudio_sl.y = 185;
		inputAudio_sl.width = 65;
		inputAudio_sl.minimum = 1;
		inputAudio_sl.maximum = 100;
		inputAudio_sl.addEventListener(SliderEvent.CHANGE, inputAudioChangeHandler);
		videoSetAsset.addChild(inputAudio_sl);
		ok_btn = new Button();
		ok_btn.width = 60;
		ok_btn.x = 180;
		ok_btn.y = 255;
		ok_btn.textField.textColor = 0xFFFFFF;
		ok_btn.label = "确定";
		cancel_btn = new Button();
		cancel_btn.width = 60;
		cancel_btn.x = 270;
		cancel_btn.y = 255;
		cancel_btn.textField.textColor = 0xFFFFFF;
		cancel_btn.label = "取消";
		var tft:TextFormat = new TextFormat("宋体");
		tft.color = 0xFFFFFF;
		ok_btn.setStyle("textFormat", tft);
		cancel_btn.setStyle("textFormat", tft);
		videoSetAsset.addChild(ok_btn);
		videoSetAsset.addChild(cancel_btn);
		
		video_cb.dataProvider = new DataProvider(Camera.names);
		audio_cb.dataProvider = new DataProvider(Microphone.names);
		videoRadio_cb.dataProvider = new DataProvider(["4:3", "16:9"]);
		
		videoSetAsset.close_btn.addEventListener(MouseEvent.CLICK, closeWinHandler);
		cancel_btn.addEventListener(MouseEvent.CLICK, closeWinHandler);
		ok_btn.addEventListener(MouseEvent.CLICK, okBtnClickHandler);
		
		videoSetAsset.audioLow_mc.addEventListener(MouseEvent.CLICK, audioQualityClickHandler);
		videoSetAsset.audioMid_mc.addEventListener(MouseEvent.CLICK, audioQualityClickHandler);
		videoSetAsset.audioHigh_mc.addEventListener(MouseEvent.CLICK, audioQualityClickHandler);
		videoSetAsset.videoLow_mc.addEventListener(MouseEvent.CLICK, videoQualityClickHandler);
		videoSetAsset.videoMid_mc.addEventListener(MouseEvent.CLICK, videoQualityClickHandler);
		videoSetAsset.videoHigh_mc.addEventListener(MouseEvent.CLICK, videoQualityClickHandler);
	}
	
	public function startPublishVideo():void
	{
		if (!publishVideo)
		{
			publishVideo = new PublishVideo(); 
			publishVideo.videoSetVO = videoSetVO;
			publishVideo.addEventListener(PublishVideoEvent.SHOW_CAMERA_BUSY, cameBusyHandler);
			publishVideo.addEventListener(PublishVideoEvent.SHOW_CAMERA_REFUSE, cameRefuseHandler);
		}
		publishVideo.setSize(AppConfig.swfWidth, (AppConfig.swfHeight - AppConfig.bottomHeight));
		(_rubyServerVO.liveType == 1) && publishVideo.startPublish(_rubyServerVO.beginTime + String(ExternalVars.event_id));
		addChild(publishVideo);
	}
	
	public function startPlayVideo():void
	{
		if (!playVideoContainer)
		{
			playVideoContainer = new PlayVideoContainer();
			playVideoContainer.startTime = int((_rubyServerVO.curTime - _rubyServerVO.startTime)/1000);
			playVideoContainer.addEventListener(PlayVideoEvent.PLAY_START, playStartHandler);
			playVideoContainer.addEventListener(PlayVideoEvent.UN_PUBLISH_NOTIFY, unPublishNotifyHandler);
		}
		playVideoContainer.setSize(AppConfig.swfWidth, (AppConfig.swfHeight - AppConfig.bottomHeight));
		playVideoContainer.startPlay(_rubyServerVO.beginTime + String(ExternalVars.event_id));
		showTip("正在等待发布视频，请稍候。。。");
		addChild(playVideoContainer);
	}
	
	public function dispose():void
	{
		/*parent && parent.removeChild(this);*/
		if (playVideoContainer)
		{
			playVideoContainer.dispose();
		}
		if (publishVideo)
		{
			publishVideo.dispose();
		}
	}
	
	public function showVideoSet():void
	{
		if (!videoSetAsset)
		{
			initVideoSet();
		}
		video_cb.selectedIndex = int(videoSetVO.cameraIndex);
		audio_cb.selectedIndex = videoSetVO.microIndex;
		videoRadio_cb.selectedIndex = videoSetVO.cameraRadioIndex;
		videoFrame_sl.value = videoSetVO.cameraFrame;
		inputAudio_sl.value = videoSetVO.microGain;
		setQualityStatus(videoSetVO.cameraQuality);
		setQualityStatus(videoSetVO.microQuality, 1);
		videoSetAsset.x = (AppConfig.swfWidth - videoSetAsset.width) * 0.5;
		videoSetAsset.y = (AppConfig.swfHeight - videoSetAsset.height) * 0.5;
		videoSetAsset.videoFrame_txt.text = String(videoSetVO.cameraFrame);
		videoSetAsset.audioValue_txt.text = String(videoSetVO.microGain);
		addChild(videoSetAsset);
		
		publishVideo && addEventListener(Event.ENTER_FRAME, checkMicroEnterFrameHandler);
	}
	
	public function resize(stageFlag:Boolean = false):void
	{
		var flag:Boolean = stage && stageFlag;
		var w:int = flag ? stage.stageWidth : AppConfig.swfWidth;
		var h:int = flag ? stage.stageHeight : AppConfig.swfHeight;
		h = h - AppConfig.bottomHeight;
		Logger.log("flag: " + flag + " w:" + w + " h: " + h);
		publishVideo && publishVideo.setSize(w, h);
		playVideoContainer && playVideoContainer.setSize(w, h);
		tipResize();
	}
	
	public function tipResize(stageFlag:Boolean = false):void
	{
		var flag:Boolean = stage && stageFlag;
		var w:int = flag ? stage.stageWidth : AppConfig.swfWidth;
		var h:int = flag ? stage.stageHeight : AppConfig.swfHeight;
		h = h - AppConfig.bottomHeight;
		if (tipAsset)
		{
			tipAsset.x = (w - tipAsset.width) * 0.5;
			tipAsset.y = h * 0.5 - 15;
		}
	}
	
	public function showTip(tipStr:String = ""):void
	{
		if (!tipStr)
		{
			tipAsset && tipAsset.parent && tipAsset.parent.removeChild(tipAsset);
			return;
		}
		if (!tipAsset)
		{
			tipAsset = new TipAsset();
			tipAsset.tip_txt.autoSize = TextFieldAutoSize.LEFT;
			tipAsset.selectable = tipAsset.mouseEnabled = false;
		}
		tipAsset.tip_txt.text = tipStr;
		tipAsset.tip_txt.width = tipAsset.tip_txt.textWidth + 4;
		tipAsset.bg_mc.width = tipAsset.tip_txt.width + 30;
		
		tipResize();
		addChild(tipAsset);
	}
	
	/**
	 * 设置质量状态
	 * @param val 质量
	 * @param type 类型0视频 1音频
	 * 
	 */	
	private function setQualityStatus(val:int, type:int = 0):void
	{
		if (type)
		{
			videoSetAsset.audioLow_mc.gotoAndStop((val==11)?2:1);
			videoSetAsset.audioMid_mc.gotoAndStop((val==22)?2:1);
			videoSetAsset.audioHigh_mc.gotoAndStop((val==44)?2:1);
		}
		else
		{
			videoSetAsset.videoLow_mc.gotoAndStop((val==70)?2:1);
			videoSetAsset.videoMid_mc.gotoAndStop((val==80)?2:1);
			videoSetAsset.videoHigh_mc.gotoAndStop((val==90)?2:1);
		}
	}
	
	/**
	 * 
	 * @param type 类型0视频 1音频
	 * @return 
	 * 
	 */	
	private function getQualityStatus(type:int = 0):int
	{
		var val:int;
		if (type)
		{
			(videoSetAsset.audioLow_mc.currentFrame == 2) && (val = 11);
			(videoSetAsset.audioMid_mc.currentFrame == 2) && (val = 22);
			(videoSetAsset.audioHigh_mc.currentFrame == 2) && (val = 44);
		}
		else
		{
			(videoSetAsset.videoLow_mc.currentFrame == 2) && (val = 70);
			(videoSetAsset.videoMid_mc.currentFrame == 2) && (val = 80);
			(videoSetAsset.videoHigh_mc.currentFrame == 2) && (val = 90);
		}
		return val;
	}
	
	//==========================================================================
	//  Event Handlers
	//==========================================================================
	private function checkMicroEnterFrameHandler(event:Event):void
	{
		var pos:int = int(10 * publishVideo.microLevel/100) + 1;
		videoSetAsset.audioCheck_mc.gotoAndStop(pos);
	}
	
	private function videoFrameChangeHandler(event:SliderEvent):void
	{
		videoSetAsset.videoFrame_txt.text = String(videoFrame_sl.value);
	}
	
	private function inputAudioChangeHandler(event:SliderEvent):void
	{
		videoSetAsset.audioValue_txt.text = String(inputAudio_sl.value);
	}
	
	private function audioQualityClickHandler(event:MouseEvent):void
	{
		if (event.currentTarget == videoSetAsset.audioLow_mc)
		{
			setQualityStatus(11, 1)
		}
		if (event.currentTarget == videoSetAsset.audioMid_mc)
		{
			setQualityStatus(22, 1);
		}
		if (event.currentTarget == videoSetAsset.audioHigh_mc)
		{
			setQualityStatus(44, 1);
		}
	}
	
	private function videoQualityClickHandler(event:MouseEvent):void
	{
		if (event.currentTarget == videoSetAsset.videoLow_mc)
		{
			setQualityStatus(70)
		}
		if (event.currentTarget == videoSetAsset.videoMid_mc)
		{
			setQualityStatus(80);
		}
		if (event.currentTarget == videoSetAsset.videoHigh_mc)
		{
			setQualityStatus(90);
		}
	}
	
	private function closeWinHandler(event:MouseEvent):void
	{
		removeEventListener(Event.ENTER_FRAME, checkMicroEnterFrameHandler);
		if (videoSetAsset && videoSetAsset.parent)
		{
			videoSetAsset.parent.removeChild(videoSetAsset);
		}
	}
	
	private function okBtnClickHandler(event:MouseEvent):void
	{
		closeWinHandler(null);
		var changeFlag:Boolean = false;
		if (videoSetVO.cameraIndex != String(video_cb.selectedIndex))
		{
			videoSetVO.cameraIndex = String(video_cb.selectedIndex);
			changeFlag = true;
		}
		if (videoSetVO.microIndex != audio_cb.selectedIndex)
		{
			videoSetVO.microIndex = audio_cb.selectedIndex;
			changeFlag = true;
		}
		if (videoSetVO.cameraRadioIndex != videoRadio_cb.selectedIndex)
		{
			videoSetVO.cameraRadioIndex = videoRadio_cb.selectedIndex;
			changeFlag = true;
		}
		if (videoSetVO.cameraFrame != videoFrame_sl.value)
		{
			videoSetVO.cameraFrame = videoFrame_sl.value;
			changeFlag = true;
		}
		if (videoSetVO.microGain != inputAudio_sl.value)
		{
			videoSetVO.microGain = inputAudio_sl.value;
			changeFlag = true;
		}
		var cameraQuality:int = getQualityStatus();
		var microQuality:int = getQualityStatus(1);
		if (videoSetVO.cameraQuality != cameraQuality)
		{
			videoSetVO.cameraQuality = cameraQuality;
			changeFlag = true;
		}
		if (videoSetVO.microQuality != microQuality)
		{
			videoSetVO.microQuality = microQuality;
			changeFlag = true;
		}
		if (changeFlag)
		{
			startPublishVideo();
		}
	}
	
	private function cameBusyHandler(event:PublishVideoEvent):void
	{
		//拒绝摄像头抛出事件
		var alert:Alert = new Alert("您的摄像头不可用或被占用，请重新设置！");
		alert.okLabel = "重新设置";
		alert.addEventListener(Event.COMPLETE, 
			function alertCompleteHandler():void
			{
				showVideoSet();
			}); 
		addChild(alert);
	}
	
	private function cameRefuseHandler(event:PublishVideoEvent):void
	{
		//拒绝摄像头抛出事件
		var alert:Alert = new Alert("您选择了拒绝摄像头设置，用户将看不到您的视频！");
		alert.okLabel = "重新选择";
		alert.addEventListener(Event.COMPLETE, 
			function alertCompleteHandler():void
			{
				Security.showSettings("privacy");
			});
		addChild(alert);
	}
	
	private function playStartHandler(event:PlayVideoEvent):void
	{
		showTip();
	}
	
	private function unPublishNotifyHandler(event:PlayVideoEvent):void
	{
		showTip("检测到上传视频已断开，正为您重试，请稍等。。。");
	}
}
}